package kline

import (
	"global/core"
	"global/libs/structs"
	"github.com/ngaut/log"
	"global/model"
	"strings"
)

type PairKlineManager struct {
	ctx  		*core.Context
	slug 		string
	symbols 	[]structs.Symbol
	coins 		[]*model.Coin
}

func NewPairKlineManager(ctx *core.Context, slug string) *PairKlineManager {
	m := &PairKlineManager{
		ctx: 		ctx,
		slug: 		slug,
		symbols: 	make([]structs.Symbol, 0),
	}
	m.loadSymbols()
	m.loadCoins()
	return m
}

func (m *PairKlineManager) Serv()  {
	maps := make(map[string]interface{})
	for _, v := range m.coins {
		maps[strings.ToLower(v.Symbol)] = nil
	}

	for _, v := range m.symbols {
		if _, ok := maps[v.From]; !ok {
			continue
		}
		go func(symbol structs.Symbol) {
			h := NewPairKlineHandle(m.ctx, m.slug, symbol, m.coins)
			h.Run()
		}(v)
	}
}

func (m *PairKlineManager) loadSymbols() {
	conn := m.ctx.GetBaseRedis().Get()
	defer conn.Close()
	var err error
	m.symbols, err = core.GetSymbolsByExchange(conn, m.slug)
	if err != nil {
		log.Fatalf("Error: load symbols failed %s", err)
	}
}

func (m *PairKlineManager) loadCoins() {
	coins, err := model.CoinModel.FindAll()
	if err != nil {
		log.Fatalf("get coins failed, err: %s", err)
	}
	m.coins = coins
}